package cn.tit.ias.util.shiro;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;

public class ValidateCodeFilter extends AccessControlFilter    {

	 /**
     * 前台提交的验证码参数名
     */
	private String jcaptchaParam = "checkCode";
	/**
     * 验证失败后存储到的属性名
     */
	private String failureKeyAttribute = "shiroLoginFailure";
	// 判断用户是否登陆，验证验证码
	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object arg2) throws Exception {

        HttpServletRequest httpRequest = WebUtils.toHttp(request);
        
        String storeCode = (String) getSubject(request, response).getSession().getAttribute("checkCode");
        String submitCode = httpRequest.getParameter(jcaptchaParam);
        System.out.println(submitCode);
		return StringUtils.equalsIgnoreCase(storeCode,submitCode);
	}

	// 验证码不正确，验证失败
	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		 //如果验证码失败了，存储失败 key 属性
		request.setAttribute(failureKeyAttribute, "jCaptcha.error");
        return true;
	}
	
	public String getFailureKeyAttribute() {
        return failureKeyAttribute;
    }
    public void setFailureKeyAttribute(String failureKeyAttribute) {
        this.failureKeyAttribute = failureKeyAttribute;
    }
    public String getJcaptchaParam() {
        return jcaptchaParam;
    }
    public void setJcaptchaParam(String jcaptchaParam) {
        this.jcaptchaParam = jcaptchaParam;
    }

}
